package com.example.demo.util;

import com.example.demo.entity.Message;

import javax.websocket.EncodeException;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketUtil {

    private static final Map<String,Session> webSocketMap = new ConcurrentHashMap<>();

    public static void addSession(String userId,Session session){
        if(webSocketMap.containsKey(userId) == false){
            webSocketMap.put(userId,session);
        }
    }

    public static void removeSession(String userId){
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
        }
    }

    /**
     * 给单个用户推送消息
     * @param userId
     * @param message
     * **/
    public static void sendMessage(String userId, Message message) throws IOException, EncodeException {
        Session session = webSocketMap.get(userId);
        if(session == null){

        }else{
            session.getBasicRemote().sendObject(message);
        }
    }

    /**
     * 向所有在线人发送消息
     * @param message
     * **/
    public static void sendMessageForAll(Message message){
        if(webSocketMap != null){
            webSocketMap.forEach((userId,session) -> {
                try {
                    sendMessage(userId,message);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (EncodeException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
